package com.whynot.frame.basic.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述: spring boot对fastjson及stringhttpmessage的转化封装，配置自动被扫描注入，支持@JSONField注释
 * spring boot默认的json解释器是jackson
 * 作者: chenyao
 * 日期: 2018-01-30.
 * 项目名称: curtain-whynot-basic
 * 版本: 1.0.0
 * JDK: since 1.8
 */
@ControllerAdvice
@Configuration
public class WebMessageConfig extends WebMvcConfigurerAdapter {


    //使用HttpMessageConverter进行http序列化和反序列化
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        MediaType mt = new MediaType(MediaType.TEXT_HTML,Charset.forName("UTF-8"));
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        supportedMediaTypes.add(mt);

        /**
         * 添加fastjson消息转化器
         * https://blog.csdn.net/u010246789/article/details/52539576
         */
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat,//是否Json数据格式化
                SerializerFeature.WriteMapNullValue,//字段数据为null的时候，是否显示在Json返回值里面
                SerializerFeature.WriteDateUseDateFormat,//时间字符串转Date
                SerializerFeature.WriteNullStringAsEmpty);//null-->>""
        fastConverter.setSupportedMediaTypes(supportedMediaTypes);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);

        /**
         * 添加stringhttp消息转化
         * http://tchen8.iteye.com/blog/993504
         */
        StringHttpMessageConverter stringCoverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        stringCoverter.setSupportedMediaTypes(supportedMediaTypes);
        converters.add(stringCoverter);
        super.configureMessageConverters(converters);
    }

}
